﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Celeriq.Common;
using Celeriq.Graphing.Core;

namespace Celeriq.RepositoryAPI.Test
{
	class Program
	{
		private const string PUBLICKEY = "<RSAKeyValue><Modulus>w/vjrGrieedJAWAoEPPqtC5ulrjCFYfuVo9XMWVf/wOJSsmPVTaJKO/o28YeznZGXq1gHHlDPZFXl12syVc/gG9x9QTnT5wl9OYDN0Az2lmKoSgaEFeHarRCO2AsSNnc4yaVFqEH/4NbABGAFT0rpHU3R62nb0TF/sgrNvct6m8=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

		static void Main(string[] args)
		{
			#region Credentials
			var credentials = new UserCredentials();
			credentials.UserName = "root";
			credentials.Password = "password";
			credentials.Password = Celeriq.Utilities.SecurityHelper.Encrypt(PUBLICKEY, credentials.PreHash);
			#endregion

			//Load Test
			const int TOTALREPOSITORY = 100;
			var baseName = "LoadTest-" + Guid.NewGuid().ToString();
			for (var ii = 0; ii < TOTALREPOSITORY; ii++)
			{
				#region Create repository if not exists

				var item = new RemotingObjectCache();
				item.Repository = new Celeriq.Common.RepositoryDefinition();
				item.Repository.FromXML(GetRepositoryTemplate());
				item.Repository.ID = new Guid(RepositoryConnection.WCFKey);
				item.Repository.Name = "Autos";
				using (var factory = Celeriq.Graphing.Core.SystemCoreInteractDomain.GetFactory("localhost"))
				{
					var server = factory.CreateChannel();
					server.SaveRepository(item.Repository, credentials);
					server.StartRepository(new Guid(RepositoryConnection.WCFKey), credentials);
				}

				#endregion

			}

			Console.WriteLine("Press any key...");
			Console.ReadLine();

		}

		private static string GetRepositoryTemplate()
		{
			var a = Assembly.GetExecutingAssembly();
			var st = a.GetManifestResourceStream("Celeriq.RepositoryAPI.Test.LoadTest.celeriq");
			var sr = new StreamReader(st);
			return sr.ReadToEnd();
		}

		private static string[] _stateArray = { "GA", "FL", "CA", "RI" };
		private static void LoadRepository(RepositoryService service, UserCredentials credentials)
		{
			const int LOOPS = 100000;
			var rnd = new Random(0);
			var list = new List<DataItem>();
			for (var ii = 0; ii < LOOPS; ii++)
			{
				var item = new DataItem();
				item.ItemArray = new object[] { 
					ii, 
					_stateArray[rnd.Next(0, _stateArray.Length)], 
					rnd.Next(2000, 2010), 
					rnd.Next(8000, 98000), 
					new GeoCode() { Latitude = rnd.Next(0, 10000) / 100.0, Longitude = rnd.Next(0, 10000) / 100.0 }, 
					new DateTime(2010, rnd.Next(1, 13), rnd.Next(1, 29)) };

				list.Add(item);

				if (ii % 100 == 0)
				{
					Console.WriteLine("Adding: " + ii);
					service.UpdateData(list, credentials);
					list = new List<DataItem>();
				}
			}

			//Straglers
			service.UpdateData(list, credentials);

		}
	}
}
